package com.steamedfish.auctioncloudgatewayserver.filter;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.steamedfish.auctioncloudgatewayserver.utils.ArrayList;
import com.steamedfish.auctioncloudgatewayserver.utils.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.PrintWriter;


@Component
public class TokenFilter implements GlobalFilter, Ordered {

    private Logger logger = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取token参数
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (StringUtils.isBlank(token)) {
            token = exchange.getRequest().getQueryParams().getFirst("Authorization");
        }

        //如果token为空，判断是否访问授权服务其，若是直接放行
        String path = exchange.getRequest().getURI().getPath();
        if (path != null && GateWayFilterRouteWhiteList.getAllPath().contains(path)) {
            return chain.filter(exchange);
        }

        if(path.contains("/auction-security-server-oauth")){
            return chain.filter(exchange);
        }

        //拆分token去掉Bearer，判断token是否为空
        String[] tokenList = null;
        if (token != null && token.startsWith("Bearer")) {
            tokenList = token.split(" ", 0);
            //获取token
            token = tokenList[1];
        } else if (token == null) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBuffer buffer = exchange.getResponse()
                    .bufferFactory()
                    .wrap(HttpStatus.UNAUTHORIZED.getReasonPhrase().getBytes());
            return exchange.getResponse().writeWith(Flux.just(buffer));
        } else {
            token = token;
        }


        logger.info("开始token权限验证");
        //验证token是否合法
        DecodedJWT jwt = TokenUtils.verifyTokenGetClaims(token);
        boolean isValidated = TokenUtils.verifyToken(token);
        if (isValidated == false) {
            //直接将登陆失败的信息返回给前端，有前端做跳转到登陆界面。
            // 登陆界面登陆拿到token以后，再来访问
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBuffer buffer = exchange.getResponse()
                    .bufferFactory()
                    .wrap(HttpStatus.UNAUTHORIZED.getReasonPhrase().getBytes());
            return exchange.getResponse().writeWith(Flux.just(buffer));

        }


        //合法则放行，不合法则丢到授权验证服务器

        return chain.filter(exchange);



    }

    @Override
    public int getOrder() {
        return 1;
    }
}